﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Xml;
using System.IO;
using System.Text;
using System.Net;
using System.Web.Security;
using System.Collections;
using System.Text.RegularExpressions;
using System.Configuration;

namespace wxDemoweb.wxModel
{
    public class wxpayHandler
    {
        //把appid，商户号和密匙放在配置文件中
        string appid = ConfigurationManager.AppSettings["appid"];
        string appkey = ConfigurationManager.AppSettings["appkey"];
        string mchid = ConfigurationManager.AppSettings["mchid"];
        private int rep = 0;
        JavaScriptSerializer js = new JavaScriptSerializer();

        /// <summary>
        /// SHA1加密字符串
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <returns>加密后的字符串</returns>
        public string SHA1(string source)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "SHA1").ToLower();
        }
        /// <summary>
        /// MD5加密字符串
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <returns>加密后的字符串</returns>
        public string MD5(string source)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5").ToLower();
        }

        /// <summary> 
        /// 生成随机字母字符串(数字字母混和) 
        /// </summary> 
        /// <param name="codeCount">待生成的位数</param> 
        /// <returns>生成的字母字符串</returns> 
        public string GenerateCheckCode(int codeCount)
        {
            string str = string.Empty;
            long num2 = DateTime.Now.Ticks + this.rep;
            this.rep++;
            Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> this.rep)));
            for (int i = 0; i < codeCount; i++)
            {
                char ch;
                int num = random.Next();
                if ((num % 2) == 0)
                {
                    ch = (char)(0x30 + ((ushort)(num % 10)));
                }
                else
                {
                    ch = (char)(0x41 + ((ushort)(num % 0x1a)));
                }
                str = str + ch.ToString();
            }
            return str;
        }
        /// <summary>
        /// DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name=”time”></param>
        /// <returns></returns>
        public int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }
        /// <summary>
        /// 获取签名
        /// </summary>
        /// <returns>sin签名</returns>
        public string getSin(Hashtable ParametersTosin, string appkey)
        {
            StringBuilder sb = new StringBuilder();
            ArrayList akeys = new ArrayList(ParametersTosin.Keys);
            akeys.Sort();
            foreach (string k in akeys)
            {
                string v = (string)ParametersTosin[k];
                if (null != v && "".CompareTo(v) != 0
                    && "sign".CompareTo(k) != 0 && "key".CompareTo(k) != 0)
                {
                    sb.Append(k + "=" + v + "&");
                }
            }
            sb.Append("key=" + appkey);
            string sign = MD5(sb.ToString()).ToUpper();
            return sign;
        }
        /// <summary>
        /// 发送统一下单数据xml包
        /// </summary>
        /// <param name="pk">请求参数包</param>
        /// <returns></returns>
        public string getDataXML(Hashtable ParametersTodata)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<xml>");
            foreach (string k in ParametersTodata.Keys)
            {
                string v = (string)ParametersTodata[k];
                if (Regex.IsMatch(v, @"^[0-9.]$"))
                {

                    sb.Append("<" + k + ">" + v + "</" + k + ">");
                }
                else
                {
                    sb.Append("<" + k + "><![CDATA[" + v + "]]></" + k + ">");
                }

            }
            sb.Append("</xml>");
            return sb.ToString();
        }
        /// <summary>
        /// 获取JS-SDK签名包
        /// </summary>
        /// <param name="appid"></param>
        //public wxHandleModel.wxJSconfig GetTicket(string url)
        //{
        //    //获取ticket的web服务
        //    //可以不用写web服务，能取到ticket就行了，但是要记得缓存
        //    wxservice.wxSoapClient wxs = new wxservice.wxSoapClient();
        //    wxs.Get_access_token(appid);
        //    string ticket = wxs.Get_access_ticket(appid, false);
        //    wxHandleModel.wxJSconfig wxconfig = new wxHandleModel.wxJSconfig();
        //    wxconfig.appId = appid;
        //    wxconfig.nonceStr = GenerateCheckCode(16); //随机字符串
        //    wxconfig.timestamp = ConvertDateTimeInt(DateTime.Now); //时间戳
        //    wxconfig.signature = SHA1("jsapi_ticket=" + ticket + "&noncestr=" + wxconfig.nonceStr + "&timestamp=" + wxconfig.timestamp + "&url=" + url);
        //    return wxconfig;
        //}
        /// <summary>
        /// 获取微信支付JS包
        /// </summary>
        /// <param name="repayId">预支付ID</param>
        /// <returns></returns>
        public wxHandleModel.wxPayconfig GetwxPay(string repayId)
        {
            wxHandleModel.wxPayconfig wxpayconfig = new wxHandleModel.wxPayconfig();
            string package = string.Format("prepay_id={0}", repayId);
            wxpayconfig.package = package;
            wxpayconfig.timestamp = ConvertDateTimeInt(DateTime.Now);
            string nostr = GenerateCheckCode(16);
            wxpayconfig.nonceStr = nostr;
            wxpayconfig.signType = "MD5";
            string stringA = string.Format(@"appId={0}&nonceStr={1}&package={2}&signType={3}&timeStamp={4}&key={5}"
                , appid, wxpayconfig.nonceStr, wxpayconfig.package, wxpayconfig.signType, wxpayconfig.timestamp, appkey);
            wxpayconfig.paySign = MD5(stringA).ToUpper();
            return wxpayconfig;
        }
        public string GetPage(string posturl, string postData)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            byte[] data = encoding.GetBytes(postData);
            // 准备请求...  
            try
            {
                // 设置参数  
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据  
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求  
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码  
                string content = sr.ReadToEnd();
                string err = string.Empty;
                return content;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return string.Empty;
            }


        }

    }
}